package com.xcity.game.activity.surprise7days;

import naga.x.game.template.Template;
import naga.x.game.template.TemplateException;
import naga.x.game.template.annotation.Excel;
import naga.x.util.CommonUtils;
import naga.x.util.NumberUtils;
import naga.x.util.StringUtils;

/**
 * 惊喜七天乐
 * @author yang.li
 *
 */
@Excel(value = "activity.xlsx", sheet = 6)
public class Surprise7DaysTemplate extends Template {

	/** 数字0~9手动概率（权重，整数，英文逗号隔开） */
	protected String manualWeight;
	protected int[] weightsForManual;

	/** 系统自动概率 */
	protected String autoWeight;
	protected int[] weightsForAuto;

	public String getManualWeight() {
		return manualWeight;
	}

	public void setManualWeight(String manualWeight) {
		this.manualWeight = manualWeight;
	}

	public String getAutoWeight() {
		return autoWeight;
	}

	public void setAutoWeight(String autoWeight) {
		this.autoWeight = autoWeight;
	}

	public int[] getWeightsForManual() {
		return weightsForManual;
	}

	public int[] getWeightsForAuto() {
		return weightsForAuto;
	}
	
	public int makeRandomNumberManually() {
		return makeRandomNumber(weightsForManual);
	}
	
	public int makeRandomNumberAutomatically() {
		return makeRandomNumber(weightsForAuto);
	}
	
	public static int makeRandomNumber(int[] weights) {
		int start = 0, end = weights.length - 1;
		int val = CommonUtils.randomInt(weights[end]);
		while (start <= end) {
			int mid = (start + end) >> 1;
			int minVal = mid > 0 ? weights[mid - 1] : 0;
			if (val < minVal) {
				end = mid - 1;
				continue;
			}
			int maxVal = weights[mid];
			if (val >= maxVal) {
				start = mid + 1;
				continue;
			}
			return mid;
		}
		return 0; // default, but impossible
	}

	@Override
	public void validate() throws TemplateException {
		weightsForManual = wrap(manualWeight);
		manualWeight = null;
		weightsForAuto = wrap(autoWeight);
		autoWeight = null;
	}
	
	private int[] wrap(String str) throws TemplateException {
		String[] strs = StringUtils.split(StringUtils.trim(str), ",");
		if (strs == null || strs.length != 10) {
			throw new TemplateException("error sheet: activity.xlsx, index: 6 -> manualWeight -> id: " + getId());
		}
		int[] arr = new int[strs.length];
		for (int i = 0; i < strs.length; i++) {
			int n = NumberUtils.parseInt(StringUtils.trim(strs[i]));
			if (n < 0) {
				throw new TemplateException("error sheet: activity.xlsx, index: 6 -> manualWeight -> id: " + getId());
			}
			if (i > 0) {
				arr[i] = arr[i - 1] + n;
			} else {
				arr[i] = n;
			}
		}
		return arr;
	}
	
	
}
